$(function() {
    // 初始化图表
    var temperatureChart = echarts.init(document.getElementById('temperatureChart'));
    var humidityChart = echarts.init(document.getElementById('humidityChart'));
    
    // 初始化数据表格
    var alarmTable = $('#alarmTable').DataTable({
        responsive: true,
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel'
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        columns: [
            { data: 'monitorId' },
            { data: 'warehouseName' },
            { data: 'storageArea' },
            { data: 'deviceId' },
            { data: 'temperature' },
            { data: 'humidity' },
            { data: 'alarmInfo' },
            { data: 'recordTime' },
            { 
                data: 'processStatus',
                render: function(data) {
                    if (data === '0') {
                        return '<span class="status-unprocessed">未处理</span>';
                    } else {
                        return '<span class="status-processed">已处理</span>';
                    }
                }
            },
            {
                data: null,
                render: function(data) {
                    if (data.processStatus === '0') {
                        return '<button class="btn btn-sm btn-primary process-btn" data-id="' + data.monitorId + '">处理</button>';
                    } else {
                        return '<button class="btn btn-sm btn-info view-btn" data-id="' + data.monitorId + '">查看</button>';
                    }
                }
            }
        ]
    });
    
    // 加载仓库下拉框选项
    loadWarehouseOptions();
    
    // 默认加载第一个仓库的数据
    $('#warehouseSelect').on('change', function() {
        var warehouseId = $(this).val();
        if (warehouseId) {
            loadMonitorData(warehouseId);
            loadMonitorStats(warehouseId);
        }
    });
    
    // 刷新按钮点击事件
    $('#refreshBtn').on('click', function() {
        var warehouseId = $('#warehouseSelect').val();
        if (warehouseId) {
            loadMonitorData(warehouseId);
            loadMonitorStats(warehouseId);
        }
    });
    
    // 处理告警按钮点击事件
    $('#alarmTable').on('click', '.process-btn', function() {
        var monitorId = $(this).data('id');
        showProcessModal(monitorId);
    });
    
    // 查看告警处理详情按钮点击事件
    $('#alarmTable').on('click', '.view-btn', function() {
        var monitorId = $(this).data('id');
        viewProcessDetail(monitorId);
    });
    
    // 保存处理按钮点击事件
    $('#saveProcessBtn').on('click', function() {
        saveProcess();
    });
    
    // 加载仓库选项
    function loadWarehouseOptions() {
        $.ajax({
            url: '/warehouse/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var options = '';
                    $.each(res.data, function(index, warehouse) {
                        options += '<option value="' + warehouse.warehouseId + '">' + warehouse.warehouseName + '</option>';
                    });
                    $('#warehouseSelect').append(options);
                    
                    // 如果有仓库，默认选中第一个并加载数据
                    if (res.data && res.data.length > 0) {
                        $('#warehouseSelect').val(res.data[0].warehouseId).trigger('change');
                    }
                }
            }
        });
    }
    
    // 加载监控数据
    function loadMonitorData(warehouseId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/latest/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    renderMonitorCards(res.data);
                    renderCharts(res.data);
                    loadAlarmData(warehouseId);
                }
            }
        });
    }
    
    // 加载监控统计数据
    function loadMonitorStats(warehouseId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/stats/' + warehouseId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    updateStatsCards(res.data);
                }
            }
        });
    }
    
    // 加载告警数据
    function loadAlarmData(warehouseId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/list',
            type: 'GET',
            data: {
                warehouseId: warehouseId,
                status: ['1', '2', '3'] // 只加载异常状态的数据
            },
            success: function(res) {
                if (res.code === 200) {
                    alarmTable.clear().rows.add(res.data).draw();
                }
            }
        });
    }
    
    // 渲染监控卡片
    function renderMonitorCards(data) {
        var cardsHtml = '';
        
        $.each(data, function(index, monitor) {
            var statusClass = 'normal';
            var statusText = '正常';
            
            if (monitor.status === '1') {
                statusClass = 'warning';
                statusText = '温度异常';
            } else if (monitor.status === '2') {
                statusClass = 'warning';
                statusText = '湿度异常';
            } else if (monitor.status === '3') {
                statusClass = 'danger';
                statusText = '温湿度均异常';
            }
            
            cardsHtml += '<div class="col-md-4 mb-3">' +
                '<div class="card monitoring-card">' +
                '<div class="card-header bg-' + statusClass + ' text-white">' +
                '<i class="fas fa-thermometer-half mr-2"></i>' + monitor.storageArea + ' - ' + monitor.deviceId +
                '</div>' +
                '<div class="card-body">' +
                '<div class="row">' +
                '<div class="col-md-6">' +
                '<div class="monitoring-count">' + monitor.temperature + ' °C</div>' +
                '<div class="text-muted">温度</div>' +
                '</div>' +
                '<div class="col-md-6">' +
                '<div class="monitoring-count">' + monitor.humidity + ' %</div>' +
                '<div class="text-muted">湿度</div>' +
                '</div>' +
                '</div>' +
                '<div class="text-muted mt-2">更新时间: ' + formatDateTime(monitor.recordTime) + '</div>' +
                '<div class="mt-2"><span class="alarm-badge ' + statusClass + '">' + statusText + '</span></div>' +
                '</div>' +
                '</div>' +
                '</div>';
        });
        
        $('#realTimeData').html('<div class="row">' + cardsHtml + '</div>');
    }
    
    // 更新统计卡片
    function updateStatsCards(data) {
        var normalCount = 0;
        var warningCount = 0;
        var dangerCount = 0;
        var totalCount = 0;
        
        $.each(data, function(index, stat) {
            if (stat.status === '0') {
                normalCount = stat.count;
            } else if (stat.status === '1' || stat.status === '2') {
                warningCount += stat.count;
            } else if (stat.status === '3') {
                dangerCount = stat.count;
            }
            totalCount += stat.count;
        });
        
        $('#normalCount').text(normalCount);
        $('#warningCount').text(warningCount);
        $('#dangerCount').text(dangerCount);
        $('#totalCount').text(totalCount);
        
        // 更新进度条
        if (totalCount > 0) {
            var normalPercent = (normalCount / totalCount * 100).toFixed(0) + '%';
            var warningPercent = (warningCount / totalCount * 100).toFixed(0) + '%';
            var dangerPercent = (dangerCount / totalCount * 100).toFixed(0) + '%';
            
            $('#normalProgress').css('width', normalPercent);
            $('#warningProgress').css('width', warningPercent);
            $('#dangerProgress').css('width', dangerPercent);
        }
    }
    
    // 渲染图表
    function renderCharts(data) {
        // 提取温度和湿度数据
        var times = [];
        var temperatures = [];
        var humidities = [];
        
        // 按时间排序
        data.sort(function(a, b) {
            return new Date(a.recordTime) - new Date(b.recordTime);
        });
        
        // 最多显示最近24小时的数据
        var recentData = data.slice(-24);
        
        $.each(recentData, function(index, item) {
            times.push(formatTime(item.recordTime));
            temperatures.push(item.temperature);
            humidities.push(item.humidity);
        });
        
        // 配置温度图表
        var temperatureOption = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['温度(°C)']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: times
            },
            yAxis: {
                type: 'value',
                name: '温度(°C)'
            },
            series: [{
                name: '温度(°C)',
                type: 'line',
                data: temperatures,
                markLine: {
                    data: [
                        {
                            name: '警戒线',
                            yAxis: 10
                        }
                    ]
                }
            }]
        };
        
        // 配置湿度图表
        var humidityOption = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['湿度(%)']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: times
            },
            yAxis: {
                type: 'value',
                name: '湿度(%)'
            },
            series: [{
                name: '湿度(%)',
                type: 'line',
                data: humidities,
                markLine: {
                    data: [
                        {
                            name: '警戒线',
                            yAxis: 80
                        }
                    ]
                }
            }]
        };
        
        // 设置图表
        temperatureChart.setOption(temperatureOption);
        humidityChart.setOption(humidityOption);
    }
    
    // 显示处理模态框
    function showProcessModal(monitorId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/detail/' + monitorId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    $('#alarmId').val(data.monitorId);
                    $('#alarmInfo').val(data.alarmInfo || '温湿度异常告警');
                    
                    // 检查modal函数是否存在
                    if (typeof $('#processAlarmModal').modal === 'function') {
                        $('#processAlarmModal').modal('show');
                    } else {
                        console.error('Bootstrap modal function is not available');
                        alert('无法显示模态框，请确保Bootstrap正确加载');
                    }
                }
            }
        });
    }
    
    // 查看处理详情
    function viewProcessDetail(monitorId) {
        $.ajax({
            url: '/warehouse/coldStorageMonitor/process/' + monitorId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    $('#alarmId').val(data.monitorId);
                    $('#alarmInfo').val(data.alarmInfo || '温湿度异常告警');
                    $('#processRemarks').val(data.processRemarks).prop('readonly', true);
                    $('#saveProcessBtn').hide();
                    
                    // 检查modal函数是否存在
                    if (typeof $('#processAlarmModal').modal === 'function') {
                        $('#processAlarmModal').modal('show');
                    } else {
                        console.error('Bootstrap modal function is not available');
                        alert('无法显示模态框，请确保Bootstrap正确加载');
                    }
                }
            }
        });
    }
    
    // 保存处理
    function saveProcess() {
        var monitorId = $('#alarmId').val();
        var processRemarks = $('#processRemarks').val();
        
        if (!processRemarks) {
            alert('请输入处理备注');
            return;
        }
        
        $.ajax({
            url: '/warehouse/coldStorageMonitor/process',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                monitorId: monitorId,
                processStatus: '1',
                processRemarks: processRemarks,
                processTime: new Date().toISOString()
            }),
            success: function(res) {
                if (res.code === 200) {
                    // 检查modal函数是否存在
                    if (typeof $('#processAlarmModal').modal === 'function') {
                        $('#processAlarmModal').modal('hide');
                    } else {
                        console.error('Bootstrap modal function is not available');
                    }
                    
                    // 刷新数据
                    var warehouseId = $('#warehouseSelect').val();
                    if (warehouseId) {
                        loadAlarmData(warehouseId);
                    }
                    
                    alert('处理成功');
                } else {
                    alert('处理失败：' + res.message);
                }
            },
            error: function() {
                alert('处理失败，请稍后重试');
            }
        });
    }
    
    // 格式化日期时间
    function formatDateTime(dateTime) {
        if (!dateTime) return '';
        return moment(dateTime).format('YYYY-MM-DD HH:mm:ss');
    }
    
    // 格式化时间
    function formatTime(dateTime) {
        if (!dateTime) return '';
        return moment(dateTime).format('HH:mm');
    }
    
    // 窗口大小变化时重新调整图表大小
    $(window).resize(function() {
        temperatureChart.resize();
        humidityChart.resize();
    });
}); 